<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import * as XLSX from 'xlsx' // 引入 xlsx 库，用于前端生成和导出 Excel 文件

// 顶部数据卡片
const stats = [
  { label: '新增用户', value: 13856, trend: -10 },
  { label: '活跃用户', value: 13856, trend: 10 },
  { label: 'DAU/MAU', value: 0.07, trend: -10 },
  { label: '启动次数', value: 87958, trend: -10 },
  { label: '单次平均使用时长', value: '00:05:00', trend: -10 },
]

// 趋势Tab
const trendTabs = [
  '新增用户', '日活跃', '周活跃', '月活跃', '启动次数', '单次平均使用时长'
]
const activeTab = ref(0)

// 日期选择
const dateRange = ref(['2021-03-13', '2021-04-12'])

// 折线图数据
const chartData = ref({
  x: [
    '2021-10-01','2021-10-02','2021-10-03','2021-10-04','2021-10-05','2021-10-06','2021-10-07','2021-10-08','2021-10-09','2021-10-10','2021-10-11','2021-10-12','2021-10-13','2021-10-14','2021-10-15'
  ],
  y: [550, 400, 450, 500, 850, 700, 500, 480, 520, 0, 600, 700, 650, 600, 650]
})

const chartRef = ref()
const initChart = () => {
  chartRef.value = echarts.init(document.getElementById('userTrendChart'))
  chartRef.value.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 20, top: 30, bottom: 30 },
    xAxis: { type: 'category', data: chartData.value.x },
    yAxis: { type: 'value' },
    series: [{
      data: chartData.value.y,
      type: 'line',
      smooth: true,
      areaStyle: { opacity: 0.15 },
      lineStyle: { color: '#409EFF', width: 2 },
      itemStyle: { color: '#409EFF' },
    }],
  })
}

// 表格数据，ref 包裹的数组，每个对象为一行
const tableData = ref([
  { date: '2025-03-21', newUser: 690, dau: 1292, wau: 6274, mau: 19206, launch: 3041, avgTime: '00:04:59' },
  { date: '2025-03-20', newUser: 500, dau: 1352, wau: 6252, mau: 19061, launch: 2894, avgTime: '00:05:02' },
  { date: '2025-03-19', newUser: 500, dau: 1218, wau: 6221, mau: 18914, launch: 2872, avgTime: '00:05:05' },
  { date: '2025-03-18', newUser: 500, dau: 1301, wau: 6205, mau: 18892, launch: 2841, avgTime: '00:05:01' },
])
const page = ref(1)
const pageSize = ref(10)
const total = ref(50)

// 导出表格数据为 Excel 文件
const handleExport = () => {
  // 1. 将表格数据（ref 取 .value）转为 Excel 工作表
  const ws = XLSX.utils.json_to_sheet(tableData.value)
  // 2. 新建一个 Excel 文件
  const wb = XLSX.utils.book_new()
  // 3. 把表格 sheet 添加到文件中，命名为“用户趋势”
  XLSX.utils.book_append_sheet(wb, ws, '用户趋势')
  // 4. 触发浏览器下载 Excel 文件，文件名为“用户趋势数据.xlsx”
  XLSX.writeFile(wb, '用户趋势数据.xlsx')
}
// 导出全部数据（统计卡片、趋势图、表格）为一个 Excel 文件
const handleExportAll = () => {
  // 1. 统计卡片 sheet：直接用 stats 数组
  const statsSheet = XLSX.utils.json_to_sheet(stats)
  // 2. 趋势图 sheet：将 x/y 合并为对象数组
  const chartSheet = XLSX.utils.json_to_sheet(
    chartData.value.x.map((x, i) => ({
      日期: x, 数值: chartData.value.y[i]
    }))
  )
  // 3. 表格 sheet
  const tableSheet = XLSX.utils.json_to_sheet(tableData.value)
  // 4. 新建 Excel 文件
  const wb = XLSX.utils.book_new()
  // 5. 依次添加三张 sheet
  XLSX.utils.book_append_sheet(wb, statsSheet, '统计概览')
  XLSX.utils.book_append_sheet(wb, chartSheet, '趋势图')
  XLSX.utils.book_append_sheet(wb, tableSheet, '用户趋势')
  // 6. 下载 Excel 文件，文件名自定义
  XLSX.writeFile(wb, '用户分析全量数据.xlsx')
}

onMounted(() => {
  setTimeout(initChart, 100)
})
</script>

<template>
  <div class="user-analysis-dashboard">
    <!-- 顶部 -->
    <div class="header-bar">
      <div class="title">用户分析</div>
      <div class="header-actions">
        <button class="export-btn" @click="handleExportAll">数据导出</button>
        <input type="date" v-model="dateRange[0]" class="date-input" />
        <span class="date-sep">至</span>
        <input type="date" v-model="dateRange[1]" class="date-input" />
      </div>
    </div>

    <!-- 用户概况 -->
    <div class="stats-section">
      <div class="stat-card" v-for="(item, i) in stats" :key="i">
        <div class="stat-value">{{ item.value }}</div>
        <div class="stat-label">{{ item.label }}</div>
        <div class="stat-trend" :class="item.trend >= 0 ? 'up' : 'down'">
          <span v-if="item.trend >= 0">▲</span>
          <span v-else>▼</span>
          {{ Math.abs(item.trend) }}%
        </div>
      </div>
    </div>

    <!-- 用户趋势 -->
    <div class="trend-section">
      <div class="trend-tabs">
        <button v-for="(tab, i) in trendTabs" :key="i" :class="['trend-tab', {active: activeTab===i}]" @click="activeTab=i">{{ tab }}</button>
      </div>
      <div id="userTrendChart" class="trend-chart"></div>
    </div>

    <!-- 用户趋势表格 -->
    <div class="table-section">
      <div class="table-header">
        <span>用户趋势</span>
        <button class="export-btn" @click="handleExport">导出</button>
      </div>
      <table class="user-table">
        <thead>
          <tr>
            <th>时间</th>
            <th>新增用户</th>
            <th>日活跃</th>
            <th>周活跃</th>
            <th>月活跃</th>
            <th>启动次数</th>
            <th>单次平均使用时长</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in tableData" :key="row.date">
            <td>{{ row.date }}</td>
            <td>{{ row.newUser }}</td>
            <td>{{ row.dau }}</td>
            <td>{{ row.wau }}</td>
            <td>{{ row.mau }}</td>
            <td>{{ row.launch }}</td>
            <td>{{ row.avgTime }}</td>
          </tr>
        </tbody>
      </table>
      <div class="table-footer">
        <div class="pagination">
          <button :disabled="page===1">&lt;</button>
          <button class="active">1</button>
          <span>...</span>
          <select v-model="pageSize">
            <option :value="10">10条/页</option>
            <option :value="20">20条/页</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.user-analysis-dashboard {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  padding: 18px 32px;
  margin-bottom: 24px;
}
.title {
  font-size: 22px;
  font-weight: 600;
  color: #222;
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
.export-btn {
  background: #409EFF;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 7px 18px;
  font-size: 14px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.2s;
}
.export-btn:hover {
  background: #66b1ff;
}
.date-input {
  border: 1px solid #e6eaf0;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 14px;
  color: #333;
}
.date-sep {
  color: #888;
  margin: 0 6px;
}
.stats-section {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}
.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  padding: 24px 0 18px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  margin-bottom: 6px;
}
.stat-label {
  font-size: 15px;
  color: #888;
  margin-bottom: 8px;
}
.stat-trend {
  position: absolute;
  right: 18px;
  top: 18px;
  font-size: 14px;
  font-weight: 500;
}
.stat-trend.up {
  color: #67C23A;
}
.stat-trend.down {
  color: #F56C6C;
}
.trend-section {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  padding: 24px 32px 8px 32px;
  margin-bottom: 24px;
}
.trend-tabs {
  display: flex;
  gap: 18px;
  margin-bottom: 12px;
}
.trend-tab {
  background: none;
  border: none;
  font-size: 15px;
  color: #888;
  padding: 6px 0;
  border-bottom: 2px solid transparent;
  cursor: pointer;
  font-weight: 500;
  transition: color 0.2s, border 0.2s;
}
.trend-tab.active, .trend-tab:hover {
  color: #F56C6C;
  border-bottom: 2px solid #F56C6C;
}
.trend-chart {
  width: 100%;
  height: 280px;
}
.table-section {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  padding: 24px 32px 18px 32px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #222;
}
.user-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 12px;
}
.user-table th, .user-table td {
  padding: 12px 10px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}
.user-table th {
  background: #fafbfc;
  color: #888;
  font-weight: 500;
}
.user-table td {
  color: #222;
}
.table-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.pagination {
  display: flex;
  align-items: center;
  gap: 4px;
}
.pagination button {
  background: #fff;
  border: 1px solid #e6eaf0;
  border-radius: 4px;
  padding: 4px 10px;
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.pagination button.active, .pagination button:hover {
  background: #409EFF;
  color: #fff;
}
.pagination button:disabled {
  color: #ccc;
  border-color: #eee;
  cursor: not-allowed;
}
.pagination select {
  border: 1px solid #e6eaf0;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
  color: #333;
  margin-left: 8px;
}
</style>